from flask import Blueprint, jsonify, request
from werkzeug.security import generate_password_hash, check_password_hash
import json
from dat import db

bp_info = Blueprint('info', __name__)


@bp_info.route('/regi')
def regi():
    password = generate_password_hash('123')
    sql = """insert into auser values (0,"李四","%s","zxcv")""" % (password)
    db.insert(sql)
    return 'ok'


@bp_info.route('/login', methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = """select * from auser where username = "%s" """ % (data['username'])
    res = db.findone(sql)
    if res:
        if check_password_hash(res['password'], data['password']):
            return jsonify({'code': 200, 'userid': res['id'], 'username': res['username'], 'sign': res['sign']})
        else:
            return jsonify(({'code': 20010, 'mes': '密码错误'}))
    else:
        return jsonify({'code': 20011, 'mes': '用户名不存在'})


@bp_info.route('/rticle', methods=['POST', 'GET'])
def rticle():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = """insert into article values (%d,"%s","%s",%d)""" % (
        0, data['title'], data['content'], int(data['userid']))
        try:
            db.insert(sql)
            return jsonify({"code": 200})
        except:
            return jsonify({'code': 20014})
    elif request.method == 'GET':
        userid = int(request.args.get('userid'))
        if userid > 0:
            sql = """select * from article where userid = %d """ % (userid)
        else:
            sql = """select * from article"""
        res = db.findall(sql)
        return jsonify({'code': 200, 'list': res})
